const db = require("../models");
const logger = require("../utils/utils.logger").logger();
const DAO = require("../dao/DAO");
const UserBalance = db.userBalance;
const UserBalanceRecord = db.userBalanceRecord;
const moment = require("moment");
// 创建用户余额信息
exports.createUserBalanceInfo = (req, res) => {
  const { userId, userBalance } = req.body;
  // 请求验证
  if (!userId)
    return res.sendResult({ data: "", code: 500, message: "用户ID不能为空！" });

  if (!userBalance)
    return res.sendResult({
      data: "",
      code: 500,
      message: "用户余额不能为空！",
    });

  const userBalanceInfo = {
    uid: userId,
    userBalance,
  };
  UserBalance.findAll({ where: { uid: userId } }).then((singleUser) => {
    if (singleUser && singleUser.uid)
      return res.sendResultAto(null, 605, "用户余额信息已存在！");
    DAO.create(UserBalance, userBalanceInfo, (data) => {
      res.sendResult(data);
    });
  });
};

// 修改用户余额信息
exports.updateUserBalanceInfo = async (req, res) => {
  const pm = req.body;
  // 请求验证
  if (!pm.userId)
    return res.sendResult({ data: "", code: 500, message: "用户ID不能为空！" });

  const balance = await UserBalance.findOne({
    where: { uid: pm.userId },
  }).then((balance) => {
    console.log(balance);
    return balance;
  });
  const amount = Number(balance.userBalance) + Number(pm.userBalance);
  const id = "CZ" + moment().format("YYYYMMDDHHmmss");
  const userBalanceRecord = {
    uid: pm.userId,
    oldBalance: Number(balance.userBalance),
    amount: Number(pm.userBalance),
    newBalance: amount,
    type: 2,
    orderId: id,
    createdAt: moment().format("YYYY-MM-DD HH:mm:ss"),
    updatedAt: moment().format("YYYY-MM-DD HH:mm:ss"),
  };
  await UserBalanceRecord.create(userBalanceRecord);
  DAO.update(
    UserBalance,
    { userBalance: amount },
    { uid: pm.userId },
    (data) => {
      logger.debug(
        `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
          pm
        )}; 响应：${JSON.stringify(data)}`
      );
      res.sendResult(data);
    }
  );
};

// 查询用户余额信息
exports.getUserBalanceInfo = (req, res) => {
  console.log(req.query);
  const pm = req.query;
  // 请求验证
  if (!pm.userId)
    return res.sendResult({ data: "", code: 500, message: "用户ID不能为空！" });
  UserBalance.findOne({ where: { uid: pm.userId } }).then((data) => {
    console.log(data);
    logger.debug(
      `${req.method} ${req.baseUrl + req.path} *** 参数：${JSON.stringify(
        pm
      )}; 响应：${JSON.stringify(data)}`
    );

    res.sendResult({ data: data, code: 200, message: "查询成功" });
  });
};
